package io.renren.modules.wyzsphone.controller;

import io.renren.RandomString;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.modules.wyzsphone.entity.UserInfo;
import io.renren.modules.wyzsphone.service.FactoryUserService;
import io.renren.modules.wyzsphone.tempEntity.TempPasswordModify;
import io.renren.modules.sys.entity.SysMenuEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.security.smartcardio.SunPCSC;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "/Login")
public class PhoneLoginController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysUserTokenService sysUserTokenService;
    @Autowired
    FactoryUserService factoryUserService;


    @RequestMapping(value = "/phoneLogin")
    @ResponseBody
    public Object phoneLogin(HttpServletRequest request, @RequestBody UserInfo userInfo){
        String username=userInfo.getUid();
        String password=userInfo.getPassword();
        SysUserEntity user = sysUserService.queryByUserName(username);
        String errInfo="success";
        //账号不存在、密码错误
        if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
            errInfo =("账号或密码不正确");
        }
        //账号锁定
//        if(user!=null&&user.getStatus() == 0){
//            errInfo =("账号已被锁定,请联系管理员");
//        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("erroInfo",errInfo);
        if(errInfo.equals("success")) {
            //生成token，并保存到数据库
            R r=sysUserTokenService.createToken(user.getUserId());
            map.put("token",r.get("token"));
            map.put("uid", username);
            map.put("email", user.getEmail());
            map.put("mobile", user.getMobile());


            List<SysMenuEntity> list=new ArrayList<SysMenuEntity>() ;
            list=sysUserService.queryAllMenus(user.getUserId());
//            map.put("MenuList", list);
        }
        map.put("erroInfo",errInfo);
        return map;
    }

    @RequestMapping("/PasswordModify")
    @ResponseBody
    public Object PasswordModify(@RequestBody TempPasswordModify tempPasswordModify) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("info","success");
        try {
            String username = tempPasswordModify.getId();
            String password = tempPasswordModify.getOldPassword();
            String newPassword = tempPasswordModify.getNewPassword();
            SysUserEntity user = sysUserService.queryByUserName(username);
            //sha256加密
            password = new Sha256Hash(password, user.getSalt()).toHex();
            //sha256加密
            newPassword = new Sha256Hash(newPassword, user.getSalt()).toHex();

            //更新密码
            int count = sysUserService.updatePassword(user.getUserId(), password, newPassword);
            if (count == 0) {
                map.put("info","error");
            }
        }catch (Exception e){
            map.put("info","error");
        }

        return map;
    }
    @RequestMapping("/firstLanding")
    public R FirstLanding(@RequestBody SysUserEntity sysUserEntity)
    {
        try {
            SysUserEntity user = sysUserService.queryByUserName(sysUserEntity.getUsername());

            if(user==null||sysUserEntity.getUsername().equals("admin"))
            {
                return R.ok().put("msg","您输入的用户名有误，请重新输入");

            }else
            {
                user.setEmail(sysUserEntity.getEmail());
                user.setMobile(sysUserEntity.getMobile());
                sysUserService.firstLanding(user);
            }
            }catch (Exception e)
            {
                return R.ok().put("msg","设置失败");

            }


        return R.ok().put("msg","设置成功");
    }

    /**
     * 保存用户
     */
    @RequestMapping("/register")
    @ResponseBody
    public R save(@RequestBody SysUserEntity user){
        ValidatorUtils.validateEntity(user, AddGroup.class);
        user.setStatus(1);
        sysUserService.register(user);
        return R.ok();
    }

    /**
     * 验证用户名
     */
    @RequestMapping("/verification/{username}")
    @ResponseBody
    public R verification(@PathVariable("username") String username) {
        SysUserEntity sysUserEntity = sysUserService.queryByUserName(username);
        if (sysUserEntity == null) {
            return R.ok();
        } else {
            return R.error("用户名已存在");
        }
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public R logout() {
        SysUserEntity user = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal());
        sysUserTokenService.logout(user.getUserId());
        return R.ok();
    }

    @RequestMapping(value = "/tokenLogin")
    @ResponseBody
    public Object tokenLogin(@RequestParam("token")String token){
        SysUserEntity user = sysUserService.queryByUserToken(token);
        String errInfo="success";
        //账号锁定
        if(user!=null&&user.getStatus() == 0){
            errInfo =("账号已被锁定,请联系管理员");
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("erroInfo",errInfo);
        if(errInfo.equals("success")) {
//            //生成token，并保存到数据库
//            R r=sysUserTokenService.createToken(user.getUserId());
//            map.put("token",r.get("token"));
            map.put("uid", user.getUsername());
            map.put("email", user.getEmail());
            map.put("mobile", user.getMobile());


            List<SysMenuEntity> list=new ArrayList<SysMenuEntity>() ;
            list=sysUserService.queryAllMenus(user.getUserId());
            map.put("MenuList", list);
        }
        map.put("erroInfo",errInfo);
        return map;
    }


}
